<template>
  <div class="app-container">
    <el-form :model="searchForm" class="search-form">
      <el-form-item label="搜索的文档" label-width="100px">
        <el-select
          v-model="searchForm.indexName"
          placeholder="搜索的文档"
          class="search-input"
          @change="selectIndex"
        >
          <el-option
            v-for="item in indexlist"
            :key="item.indexName"
            :label="showLabel(item)"
            :value="item.indexName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="查询条件" label-width="100px">
        <el-select v-model="searchForm.boolType">
          <el-option label="should" value="should"></el-option>
          <el-option label="must_not" value="must_not"></el-option>
          <el-option label="must" value="must"></el-option>
        </el-select>
        <el-select
          v-model="searchForm.fieldValue"
          class="search-left"
          @change="selectField"
        >
          <el-option
            v-for="item in fieldList"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="searchForm.opType"
          class="search-left"
          v-if="showOp == true"
          @change="selectOp"
        >
          <el-option
            v-for="item in opList"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
        <!-- qual -->
        <el-input
          v-model="searchForm.qual"
          placeholder=""
          v-if="showQual"
          class="search-left"
          style="width: 200px"
        ></el-input>
      </el-form-item>
      <el-form-item v-if="showRange" label-width="100px">
        <el-select v-model="searchForm.rangeGtType">
          <el-option label="gt" value="gt"></el-option>
          <el-option label="gte" value="gte"></el-option>
        </el-select>
        <el-input
          v-model="searchForm.rangeStart"
          class="search-left"
          style="width: 200px"
        ></el-input>
        <el-select v-model="searchForm.rangeLtType" class="search-left">
          <el-option label="lt" value="lt"></el-option>
          <el-option label="lte" value="lte"></el-option>
        </el-select>
        <el-input
          v-model="searchForm.rangeEnd"
          class="search-left"
          style="width: 200px"
        ></el-input>
      </el-form-item>
      <el-form-item v-if="showFuzzy" label-width="100px">
        <el-input
          v-model="searchForm.fuzzyValue1"
          style="width: 200px; margin-left: 0"
        ></el-input>
        <el-select v-model="searchForm.fuzzyType" class="search-left">
          <el-option label="max_expansions" value="max_expansions"></el-option>
          <el-option label="min_similarity" value="min_similarity"></el-option>
        </el-select>
        <el-input
          v-model="searchForm.fuzzyValue2"
          class="search-left"
          style="width: 200px"
        ></el-input>
      </el-form-item>
      <el-form-item label-width="100px">
        <el-button
          @click.prevent="addDomain()"
          class="search-left"
          style="margin-left: 0"
          >+</el-button
        >
        <el-button @click.prevent="removeDomain()">-</el-button>
      </el-form-item>
      <el-form-item label-width="100px">
        <el-button type="primary" @click="onSearch">查询</el-button>
      </el-form-item>
    </el-form>
    <div v-if="tableData.total > 0">
      <el-table :data="tableData.data" style="width: 100%" border>
        <el-table-column
          v-for="colitem in tableData.tableCols"
          :key="colitem"
          :prop="colitem"
          :label="colitem"
          :formatter="colFormat"
        >
        </el-table-column>
        <el-table-column
          label="操作"
          width="200">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleDelete(scope.row)">文档删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        style="margin-top: 10px"
        layout="sizes, prev, pager, next"
        :page-sizes="[10, 20, 30, 50, 100]"
        :page-size="tableData.pageSize"
        :current-page.sync="tableData.currentPage"
        :total="tableData.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import DropdownMenu from "@/components/Share/DropdownMenu";
import { allindex, docSearch,docDelete } from "@/api/elastic";

export default {
  name: "BasicQuery",
  components: { DropdownMenu },
  data() {
    return {
      searchForm: {
        indexName: "",
        boolType: "must",
        fieldValue: "match_all",
        opType: "",
      },
      indexlist: [],
      fieldList: [],
      opList: [],
      showOp: false,
      showQual: false,
      showRange: false,
      showFuzzy: false,
      tableColsType:{}, 
      tableData: {
        total: 0,
        data: [],
        tableCols: [],
        pageSize: 10,
        currentPage: 1,
      },
    };
  },
  created() {
    this.getlist();
  },
  methods: {
    onSearch() {
      console.log(this.searchForm);
      let _self = this;
      let _from = (this.tableData.currentPage - 1) * this.tableData.pageSize;
      docSearch(this.searchForm.indexName, {
        from: _from,
        size: this.tableData.pageSize,
        query: this.searchForm
      }).then((res) => {
        _self.tableData.total = parseInt(res.data.total);
        _self.tableData.data = res.data.data;
        _self.tableData.tableCols = res.data.tableCols;
        _self.tableColsType = res.data.tableColsType;
        _self.defaultFieldList();
        res.data.tableCols.forEach(item => {
          let typeKey = item;
          if (item.indexOf(".") >= 0) {
            typeKey = item.split(".")[0];
          }
          if (_self.tableColsType[typeKey]) {
            _self.fieldList.push({ label: item, value: item, fieldType: _self.tableColsType[typeKey].type });
          } else {
            _self.fieldList.push({ label: item, value: item });
          }
          
        });
      });
    },
    getlist() {
      const _self = this;
      allindex()
        .then((res) => {
          _self.indexlist = res.data;
          if (res.data.length > 0) {
            _self.searchForm.indexName = res.data[0].indexName;
            _self.onSearch();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    showLabel(item) {
      return item.indexName + "(" + item.docCount + ")个文档";
    },
    defaultFieldList() {
      this.fieldList = [];
      this.fieldList.push({ label: "match_all", value: "match_all", fieldType: "match_all" });
      this.fieldList.push({ label: "_all", value: "_all", fieldType: "_all" });
    },
    selectIndex() {
      this.onSearch();
    },
    selectField(event) {
      let fieldItem = null;
      if (event) {
        fieldItem = this.fieldList.find((item) => {
          return item.value == event;
        });
      }
      let fieldType = fieldItem.fieldType;
      var ops = [];
      if (fieldType === "match_all") {
      } else if (fieldType === "_all") {
        ops = ["query_string"];
      } else if (
        fieldType === "string" ||
        fieldType === "text" ||
        fieldType === "keyword"
      ) {
        ops = [
          "term",
          "wildcard",
          "prefix",
          "fuzzy",
          "range",
          "query_string",
          "text",
          "missing",
        ];
      } else if (
        fieldType === "long" ||
        fieldType === "integer" ||
        fieldType === "float" ||
        fieldType === "byte" ||
        fieldType === "short" ||
        fieldType === "double"
      ) {
        ops = ["term", "range", "fuzzy", "query_string", "missing"];
      } else if (fieldType === "date") {
        ops = ["term", "range", "fuzzy", "query_string", "missing"];
      } else if (fieldType === "geo_point") {
        ops = ["missing"];
      } else if (fieldType === "ip") {
        ops = ["term", "range", "fuzzy", "query_string", "missing"];
      } else if (fieldType === "boolean") {
        ops = ["term"];
      }
      this.opList = ops;
      if (ops.length == 0) {
        this.showOp = false;
        this.showQual = false;
      } else {
        this.searchForm.opType = this.opList[0];
        this.showOp = true;
        this.selectOp(this.searchForm.opType);
      }
    },
    selectOp(opv) {
      this.showQual = false;
      this.showRange = false;
      this.showFuzzy = false;
      if (
        opv === "term" ||
        opv === "wildcard" ||
        opv === "prefix" ||
        opv === "query_string" ||
        opv === "text"
      ) {
        // show qual
        this.showQual = true;
      } else if (opv === "range") {
        this.showRange = true;
      } else if (opv === "fuzzy") {
        this.showFuzzy = true;
      }
    },
    addDomain() {},
    removeDomain() {},
    handleCurrentChange(val) {
      this.tableData.currentPage = val;
      this.onSearch();
    },
    handleSizeChange(val) {
      this.tableData.pageSize = val;
      this.onSearch();
    },
    colFormat(row, column, cellValue, index) {
      if (cellValue instanceof Array) {
        return cellValue.join(",");
      } else if (cellValue === true || cellValue === false){
        return cellValue + "";
      } else {
        return cellValue;
      }
    },
    handleDelete(row) {
      let _self = this;
      docDelete(row.indexName, row.docId).then(res=>{
        _self.getlist();
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.search-input {
  width: 300px;
}
.search-left {
  margin-left: 10px;
}
</style>
